//在线预订
//@Author yanglong

var wx_user = {};

//监听键盘点击事件
$('.num_add').on("click",function(){
	num = $(this).text();
	value = $(this).val();
	remainNum = $('#num').text();
	
	//num,value都为空,则是删除
	if((value == '' || value == null) && (num == '' || num == null)){
		remainNum = remainNum.substring(0,remainNum.length-1);
		if(remainNum<1){
			remainNum = 0;
		}
	}
	else if(value == "确定"){
		// console.log('确定');
	}
	//num值为数字，且value为空，这是点击数字键
	else if((num != '' || num != null) && (value == '' || value == null)){
		if(remainNum>0){
			remainNum = remainNum+num;
		}
		else{
			remainNum = num;
		}
	}

	if(remainNum>100){
		util_alert_dialog('人数须介于1-100之间');
	}
	else{
		$('#num').text(remainNum);
	}

	//人数大于0，确定按钮变色并且可以点击
	if(remainNum>0){
		$('input[name="Calculator"]').css({
			'background-color':'#F29B47'
		});
	}else{
		$('input[name="Calculator"]').css({
			'background-color':'#d8d8d8'
		});
	}
})

//键盘填写人数，单击确定按钮
$('.btn_confirm_num').click(function(){
	remainNum = $('#num').text();
	if(remainNum<=0){
		util_alert_dialog('请填写人数');
	}
	//将总人数写入全局变量
	else{
		util_alert_dialog('正在提交...',false);
		$.post(host+'book/?cid='+cid,{act:'people_num',people_num:remainNum},function(data){
			console.log(data);
			if(data.status==1){
				util_close_dialog();
				wx_user.people_num = remainNum;

				$('.step_num').addClass('hidden');
				$(".step_phone").removeClass('hidden');
				// console.log(wx_user);	
				return true;
			}
			if(data.status==0){
				util_alert_dialog(data.msg);
			}
		},'json');		
	}
})

//确认提交手机号
$('input[name="btn_confirm_phone"]').click(function(){
	var phone = $('input[name="phone"]').val();
	re = /^1[3,4,5,7,8]\d{9}$/;
	if(re.test(phone)){
		util_alert_dialog('正在提交...',false);
		$.post(host+'book/?cid='+cid,{act:'phone',phone:phone},function(data){
			console.log(data);
			if(data.status==1){
				util_close_dialog();
				wx_user.phone=phone;
				$(".step_phone").addClass('hidden');
				$(".step_products").removeClass('hidden');
				return true;
			}
			if(data.status==0){
				util_alert_dialog(data.msg);
			}
		},'json');
	}
	else{
		util_alert_dialog('请填写正确的手机号');
	}
})

//商品列表、会员中心切换
$('.tab_nav li').click(function(){
	num = $(this).index();
	$('.step_switch_'+num).removeClass('hidden').siblings().addClass('hidden');
	//动态生成订单列表
	if(num==1){
		order_list(1);
	}
})

//购物清单
//添加类下面的商品，类显示数量
var products = [];//所有已点的商品
var list = [];//存放所有商品
var remark = '';
//加入购物车
function addCart(pid,type,cat_id){
	num = parseInt($('.'+pid).text());//当前商品数量
	sum = parseInt($('.left_con_'+cat_id+' span').text());//当前类商品数量
	price = Number(parseFloat($('.price_'+pid).text())*100);//当前商品单价
	cart_price= Number(parseFloat($('.new_price span').text())*100);//商品总价
	cart_num= parseInt($('.cart_icon span').text());//商品总数量
	if(num == '' || num == null){
		num = 0;
	}
	if(sum == '' || sum == null){
		sum = 0;
	}
	if(type == "add"){
		num++;
		sum++;
		cart_price = cart_price + price;
		cart_price = (cart_price/100).toFixed(2);
		// console.log(cart_price);
		cart_num++;
	}
	else if(type == "reduce"){
		num--;
		sum--;
		cart_price = cart_price - price;
		cart_price = (cart_price/100).toFixed(2);
		cart_num--;
		if(num <= 0){
			$('.cart_product_'+pid).remove();//针对购物车减少为0时
		}
	}
	$('.sum_'+pid).text(num);//单个商品数量
	$('.left_con_'+cat_id+' span').text(sum);//一个类的商品数量
	$('.cart_icon span').text(cart_num);//总商品数量
	$('.new span').text(cart_price);//总商品价格
	$('.old span').text(cart_price);//总商品价格

	if(num>0){
		$('.product_'+pid+' .reduce').removeClass('hidden');
		$('.product_'+pid+' .sum_'+pid).removeClass('hidden');
		$('.note').css({
			"display":"inline-block"
		})
	
	}
	else{
		$('.product_'+pid+' .reduce').addClass('hidden');
		$('.product_'+pid+' .sum_'+pid).addClass('hidden');	
		$('.list_product_id_'+pid).addClass('hidden');
		$('.note').css({
			"display":"none"
		})
	}
	//总数小于零，购物车清空
	if(cart_num>0){
		$('.foot_btn').removeClass('hidden');
	}
	else{
		$('.foot_btn').addClass('hidden');
	}
	//类总数小于零，类清空
	if(sum >0){
		$('.left_con_'+cat_id+' span').removeClass('hidden');
	}
	else{
		$('.left_con_'+cat_id+' span').addClass('hidden');
	}

	title = $('.product_'+pid+' p').text();//当前商品的描述
	price = $('.price_'+pid).text();//当前商品的单价
	// wx_user['cart_num'] = {'cart_num':cart_num};
	wx_user.cart_price = cart_price;
	products[pid] = {'cat_id':cat_id,'pid':pid,'num':num,'title':title,'price':price};
	cat_name = $('.list_con_'+cat_id+'>p').text();//当前商品的描述

	wx_user['products'] = {'products':products};
	// console.log(products);

	saveGoods(pid,num,title,price,cat_id,cat_name,remark);
	// console.log(list);
}

//保存商品数据
function saveGoods(pid,num,title,price,cat_id,cat_name,remark){
	var getCate = false;
	var getGoods = false;
	var cateIndex = 0;
	// console.log(list);
	for(var i = 0; i<list.length ; i++){
		if (getGoods) {
			break;
		}
		var cate = list[i];
		if (cate) {
			if (cate.id == cat_id) {
				cateIndex = i;
				getCate = true;
				for(var j = 0 ; j<cate.goods.length ; j++){
					var goods = cate.goods[j];
					if (goods.id == pid) {
						getGoods = true;
						if (num <= 0) {
							cate.goods.splice(j,1);
							if (cate.goods.length == 0 ) {
								list.splice(i,1);
							}
							getGoods = true;
						}else{
							getGoods = true;
							goods.num = num;
						}
						goods.remark = remark;
						break;
					}
				}
			}
		}
	}
	if (!getCate) {
		var cate = {};
		cate.id = cat_id;
		cate.name = cat_name;
		var goods = {};
		goods.id = pid;
		goods.cat_id = cat_id;
		goods.num = num;
		goods.title = title;
		goods.price = price;
		goods.remark = remark;
		cate.goods = new Array();
		cate.goods.push(goods);
		list.push(cate);
	}
	else if(!getGoods){
		var goods = {};
		goods.id = pid;
		goods.cat_id = cat_id;
		goods.num = num;
		goods.title = title;
		goods.price = price;
		goods.remark = remark;
		list[cateIndex].goods.push(goods);
	}

}

//点击图片，查看单个商品
var remarks = [];//所有的备注
var pid;//当前操作的商品
var cat_id;//当前操作的商品
$('.list_con img').click(function(){
	$('.pic_fg,.pic_view').css({
		'display':'inline-block'
	});
	//查看图片的弹出框图片的高度
    var pvwidth=$('.pic_view').width()+'px';
    $('.pic_view>img').css('width',pvwidth);
    $('.pic_view>img').css('height',pvwidth);
    //查看图片设置弹出框的高度定位
    var pvheight=$('.pic_view').height();
    $('.pic_view').css('margin-top',-pvheight/2+'px');
	//动态修改当前商品的信息
	cat_id = $(this).parents('ul').attr('cat_id');//当前商品类id	
	pid = $(this).parent().attr('pid');//当前商品id
	src = $(this).attr('src');//当前商品图片
	title = $(this).next().text();//当前商品的描述
	price = $('.price_'+pid).text();//当前商品的单价
	sum = $('.'+pid).text();//当前商品数量
	if(sum<=0){
		$('.note').css({
			"display":"none"
		})
	}else{
		$('.note').css({
			"display":"inline-block"
		})
	}
	$('.pic_v').addClass('product_'+pid);//0和减号的显示影藏
	$('.'+pid).removeClass(pid);//删除列表里面商品的数量，避免重复度数据
	$('.pic_view img').attr("src",src);//图片
	$('.pic_view .big').text(title);//描述
	$('.small .price').text(price);//价格
	$('.pic_v .sum').text(sum).addClass(pid).addClass('sum_'+pid);//在计算中通过pid获取商品数量，通过sum_pid写入商品数量
	reduce = "addCart("+pid+",'reduce',"+cat_id+")";//减少
	add = "addCart("+pid+",'add',"+cat_id+")";//增加
	$('.pic_v .reduce').attr("onclick",reduce);
	$('.pic_v .add').attr("onclick",add);
	$('.con').text(remarks['remarks_'+pid]);//备注初始值
})

//添加备注
$('.note_content span').click(function(){
	remark = $('input[name="remark"]').val();//备注上已有的内容
	if(remark != undefined && remark != null && remark != ""){
		remark = remark+'，'+$(this).text();
	}else{
		remark = $(this).text();
	}
	
	$('input[name="remark"]').val(remark);
})

//保存备注
$('.note_text_wrap span').click(function(){
	$('.con').text($('input[name="remark"]').val());
	$('.note_fg,.add_note').css({
		'display':'none'
	});
	$('.note span').css({
		'display':'inline-block'
	});
	remarks['remarks_'+pid] = $('input[name="remark"]').val();
	// console.log(list);

	saveGoods(pid,num,title,price,cat_id,cat_name,remark)
	$('input[name="remark"]').val('');//保存后，将填写框内容清空
	remark = '';

})

//查看购物车
$('.cart_icon').click(function(){
	console.log(list);
	html = '';
	$('.xc_con ul').html(html);
	for(i=0;i<=list.length;i++) {
   		o = list[i];
   		if(o != undefined && o != null && o!= ''){
   			// console.log(p.goods);
   			c = o.goods;
   			for(j=0;j<=c.length;j++){
   				p=c[j]
   				if(p != undefined && p != null && p != ''){
   					// console.log(p[j]);
   					html += '<li class="cart_product_'+p.id+'">'+
		                    '<p>'+p.title+'</p>'+
		                    '<span>￥'+p.price+'</span>'+
		                    '<div class="add_sum">'+
		                        '<span onclick="addCart('+p.id+',\'reduce\','+p.cat_id+')" class="reduce "></span>'+
		                        '<span class="sum sum_'+p.id+'">'+p.num+'</span>'+
		                        '<span onclick="addCart('+p.id+',\'add\','+p.cat_id+')" class="add"></span>'+
		                    '</div>'+
		                '</li>';
   				}
   				
   			}
   		}
 	
	}
	$('.xc_con ul').append(html);
	$('.xc_fg,.xc_con').css({
		'display':'inline-block'
	})
})

//点击空白处收起购物车
$('.xc_fg').click(function(){
	$('.xc_fg,.xc_con').css({
		'display':'none'
	})
});

//step4 确认购物车
//确认购物车
$('.btn_confirm_cart').click(function(){
	console.log(list);
	html = '';
	$('.xc_con ul').html(html);
	$('.xc_fg,.xc_con').css({
		'display':'none'
	})//隐藏购物车列表
	$('.order_lists').html(html);
	for(i=0;i<=list.length;i++){
		cat = list[i];
		total = 0;
		if(cat != undefined && cat != null && cat != ''){
			html += '<ul class="list_cat_id_'+cat.id+'">'+
                    '<p>'+cat.name+'(共<span class="total_'+cat.id+'">'+cat.goods.length+'</span>份)</p>';
	        for(j=0;j<=cat.goods.length;j++){
	        	goods = cat.goods[j];
	        	if(goods != undefined && goods != null && goods != ''){
	        		html += '<li class="list_product_id_'+goods.id+'">'+
                        '<p>'+goods.title+'</p>'+
                        '<span>￥'+goods.price+'/位</span>'+
                        '<div class="add_sum">'+
                            '<span onclick="addCart('+goods.id+',\'reduce\','+cat.id+')" class="reduce "></span>'+
		                        '<span class="sum sum_'+goods.id+'">'+goods.num+'</span>'+
		                        '<span onclick="addCart('+goods.id+',\'add\','+cat.id+')" class="add"></span>'+
                        '</div>'+
                    '</li>';
	        	}
	        	total = total + num;
	        	$('total_'+cat.id).text(total);
	        }
	        html += '</ul';
		}
		
	}
	$('.order_lists').html(html);
	$('.step_products').addClass('hidden');
	$('.step_cart').removeClass('hidden');

})

//发票信息
$('input[name="fp"]').blur(function(){
	fp =$(this).val();
	wx_user.fp=fp;
	console.log(wx_user);
})

//返回选菜
$('.icon-angle-left_order').click(function(){
	$('.step_products').removeClass('hidden');
	$('.step_cart').addClass('hidden');
})

//确认订单 显示选桌和是否到店
$('.btn_confirm_order').click(function(){
	util_alert_dialog('正在提交...',false);
	write_order(0);
	//$('.step_table_num').removeClass('hidden');
})

//取消
$('.cancel').click(function(){
	$('.step_table_num').addClass('hidden');
	$('.table_wrap').css({
		"z-index":'2300'
	})
})

//step5 确认订单
//已到店
$('.ngdialog_confirm p:first').click(function(){
	$('.table_wrap').css({
		"z-index":'2300'
	})
})

//确认桌号，并把订单信息写入数据库
$('.sure').click(function(){
	table_num = $('select[name=table_num]').val();
	wx_user.table_num = table_num;
	write_order(1);
})

//未到店
$('.keep').click(function(){
	write_order(0);
})

//订单写入数据库
//type 1 到店 0 为到店
function write_order(type){
	$.post(host+'book/?cid='+cid,{
		'act':'write_order',
		'products':list,
		'people_num':wx_user.people_num,
		'cart_price':wx_user.cart_price,
		'table_num':wx_user.table_num,
		'phone':wx_user.phone,
		'order_id':wx_user.order_id,
		'fp':wx_user.fp,
		'type':type
	},function(data){
		util_close_dialog();
		if(data.status != 0){
			//写入成功,进入订单列表
			//删除所有全局标量，
			//wx_user.cart_price = '';
			//wx_user.products = [];
			//wx_user = {};
			products = [];
			list = new Array();
			remark = '';
			remarks = [];//所有的备注
			$('.sum').text(0);//单个商品数量
			$('.left_con span').text(0);//一个类的商品数量
			$('.cart_icon span').text(0);//总商品数量
			$('.new span').text(0);//总商品价格
			$('.old span').text(0);//总商品价格
			$('.reduce').addClass('hidden');//隐藏减号
			$('.sum').addClass('hidden');//隐藏0
			$('.note').css({
				"display":"none"
			})
			$('.left_con span').addClass('hidden');
			$('.step_table_num,.step_cart').addClass('hidden');
			$('.step_order_info').removeClass('hidden');
			order_info(data.oid);
		}else{
			alert(data.msg);
		}
	},"JSON")
}

//下单页面返回上一页只能到点菜页面
$('.icon-angle-left_details,input[name="details_add"]').click(function(){
	step_order_list();
	order_list(1);
	/*
	$('.step_products').removeClass('hidden');
	$('#details').addClass('hidden');
	$('.info_list').html('');
    $('.order_info>ul').html('');
    $('.order_price').text('0');
    $('.foot_btn_zhi input').attr('order_id','');
	*/
})

//查看订单状态
// $('.order_state').click(function(){
// 	$('#details').addClass('hidden');
// 	$('#state').removeClass('hidden');
// })

//订单状态返回上一页到订单详情
$('.icon-angle-left-state').click(function(){
	$('#details').removeClass('hidden');
	$('#state').addClass('hidden');
});